/*
 * Copyright (c) 2007 Team and Concepts Limited.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Team and Concepts Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY TEAM AND CONCEPTS LIMITED ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TEAM AND CONCEPTS LIMITED BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.editgrid.api.client;

import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class EditGridHttpRequest {
	private String apiToken;
	private String appId;
	private HttpClient http;
	private HttpMethod method;
	private InputStream requestBodyStream;
	
	public EditGridHttpRequest(String method, URI uri, String appId) throws URIException {
		if (uri.getQuery() == null || uri.getQuery().equals("")) {
			uri = new URI(uri + "?app=" + appId, true);
		} else {
			uri = new URI(uri + "&app=" + appId, true);
		}
		this.http = new HttpClient();
		
		if (method.equals("GET")) {
			this.method = new GetMethod(uri.toString());
		} else if (method.equals("POST")) {
			this.method = new PostMethod(uri.toString());
		} else if (method.equals("PUT")) {
			this.method = new PutMethod(uri.toString());
		} else if (method.equals("DELETE")) {
			this.method = new DeleteMethod(uri.toString());
		} else {
			throw new IllegalArgumentException(method + " is not supported.");
		}
		this.appId = appId;
	}
	
	public String getApiToken() {
		return this.apiToken;
	}
	
	public void setApiToken(String apiToken) {
		this.apiToken = apiToken;
	}
	
	public String getAppId() {
		return this.appId;
	}
	
	public Header[] getHeaders() {
		return this.method.getRequestHeaders();
	}
	
	public String getMethod() {
		return this.method.getName();
	}
	
	public URI getRequestUri() throws URIException{
		return this.method.getURI();
	}
	
	public String getContentType() {
		return this.method.getRequestHeader("Content-Type").getValue();
	}
	
	public void setContentType(String contentType) {
		this.method.setRequestHeader("Content-Type", contentType);
	}
	
	public InputStream getRequestBodyStream() {
		return this.requestBodyStream;
	}
	
	public void setRequestBody(byte[] value) {
		this.requestBodyStream = new ByteArrayInputStream(value);
	}
	
	public void setRequestBody(String value) {
		try {
			this.requestBodyStream = new ByteArrayInputStream(value.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException();
		}
	}
	
	public void setRequestBody(InputStream stream) {
		this.requestBodyStream = stream;
	}
	
	public EditGridHttpResponse getResponse() throws IOException, HttpException, EditGridServiceException {
		if (this.apiToken != null) {
			this.method.setRequestHeader("X-EditGrid-Authorization", this.apiToken);
		}
		
		if (this.method instanceof EntityEnclosingMethod) {
			RequestEntity entity = new InputStreamRequestEntity(this.requestBodyStream);
			EntityEnclosingMethod eemethod = (EntityEnclosingMethod) this.method;
			eemethod.setRequestEntity(entity);
		}
		
		this.http.executeMethod(this.method);
		if (this.method.getResponseHeader("X-EditGrid-API-Version") == null) {
			throw new EditGridServiceException(EditGridServiceException.ServiceNotAvailable, "Service not available");
		}
		return new EditGridHttpResponse(this.method);
	}
}
